import os
import random

from google.appengine.ext.ndb import model

import webapp2
import jinja2

import gatling

env = jinja2.Environment(loader=jinja2.FileSystemLoader(
    os.path.join(os.path.dirname(__file__), 'templates')))


class GuestBook(model.Model):
  book_name = model.StringProperty()


class GuestBookUser(model.Model):
  user_name = model.StringProperty(indexed=False)
  user = model.UserProperty()


class GuestBookMessage(model.Model):
  user_model = model.KeyProperty('GuestBookUser')
  user_name = model.StringProperty(indexed=False)
  text = model.StringProperty(indexed=False)


class BaseHandler(webapp2.RequestHandler):
  def render_template(self, filename, content_type=None, **template_args):
    template = env.get_template(filename)
    self.response.write(template.render(**template_args))
    if content_type:
      self.response.headers['Content-Type'] = content_type


class ListingHandler(BaseHandler):
  def get(self):
    guestbooks = []

    for guestbook in GuestBook.query():
      message_list = []
      for message in GuestBookMessage.query(ancestor=guestbook.key):
        message_list.append(message)
      guestbooks.append({
          'name': guestbook.book_name,
          'messages': message_list,
          })
    self.render_template('listing.txt', content_type='text/plain',
                         guestbooks=guestbooks)


class BootstrapHandler(webapp2.RequestHandler):
  def get(self):
    users = [GuestBookUser.get_or_insert(user.lower(), user_name=user)
             for user in ('Greg', 'Nick', 'Cayden', 'Peter')]

    def txn():
      messages = ['Message %d' % i for i in xrange(10)]

      guestbook = GuestBook(book_name='Awesome guestbook')
      guestbook.put()

      for i in xrange(random.randint(1, 10)):
        user = random.choice(users)
        message = GuestBookMessage(parent=guestbook.key,
                                   user_name=user.user_name,
                                   user_model=user.key,
                                   text=random.choice(messages))
        message.put()
    model.transaction(txn)

    self.response.set_status(302)
    self.response.headers['Location'] = '/listing'


class IndexHandler(BaseHandler):
  def get(self):
    self.render_template('index.html')

  def post(self):
    pipeline = gatling.DatastoreDumpPipeline(
        mapreduce_name='guestbook_dump',
        kind=self.request.POST['kind'],
        shards=2)
    pipeline.start()
    self.redirect("%s/status?root=%s" % (pipeline.base_path, pipeline.pipeline_id))


_Routes = [
    (r'/listing', ListingHandler),
    (r'/bootstrap', BootstrapHandler),
    (r'/', IndexHandler),
]
application = webapp2.WSGIApplication(_Routes, debug=True)
